import {
  PaymentInfo,
  PaymentOrder,
  SupportToken,
  UpdateOrderInfo,
} from '../../types/order';
import {AuthSig} from '../../types/user';
import Config from 'react-native-config';
import {parseValue} from '../../utils';
import {TokenPrice} from '../../types/token';

export const registerCallback = async (authSig: AuthSig) => {
  return await fetch(Config.BACKEND_HOST + '/api/register/callback', {
    method: 'POST',
    headers: {
      message: authSig.message,
      signature: authSig.signature,
    },
  });
};

export const requestPrepareSignUsername = async (username: string) => {
  try {
    const response = await fetch(
      Config.BACKEND_HOST + '/api/register/username/prepare_sign',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({username}),
      },
    );
    return await response.json();
  } catch (error) {
    console.log(error);
  }
};

export const selectUniwebOrder = async (orderId: string) => {
  try {
    const response = await fetch(
      Config.UP_HOST +
        '/zcloak-rest/uniwebOrder/selectUniwebOrder?id=' +
        orderId,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    const resObj = await response.json();
    if (resObj['code'] == '000000') {
      const data = resObj['data'];
      const tokenList = data['storeCryptoMethodDtoList'];
      const supportTokenList: SupportToken[] = [];
      for (let i = 0; i < tokenList.length; i++) {
        const token = tokenList[i];
        supportTokenList.push({
          symbol: token['cryptoSymbol'],
          isNative: (token['cryptoSymbol'] as string).toUpperCase() == 'SOL',
          address: token['cryptoAddress'],
        });
      }

      const orderInfo: PaymentOrder = {
        orderId: orderId,
        orderValue: parseValue(Number(data['amount']) + '', 2),
        currency: data['currency'],
        secondVerification: data['secondVerification'] != 'NO',
        merchantName: data['storeName'],
        paymentStatus: data['paymentStatus'],
        merchantSolanaAddress: data['walletAddress'],
        defaultPaymentToken: data['cryptoSymbol'],
        supportTokenList: supportTokenList,
      };

      return orderInfo;
    } else {
      return null;
    }
  } catch (error) {
    console.log('selectUniwebOrder error', error);
  }

  return null;
};

export const getCheckoutConfiguration = async (): Promise<string | null> => {
  try {
    const response = await fetch(
      Config.UP_HOST + '/zcloak-rest/checkout/getConfiguration',
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    const result = await response.json();
    if (result['code'] == '000000') {
      return result['data']['checkoutPublicApikey'];
    } else {
      return null;
    }
  } catch (error) {
    console.log('getCheckoutConfiguration', error);
  }

  return null;
};

export const coinPriceQuery = async (
  tokenSymbol: string,
  tokenAddress?: string,
) => {
  console.log(tokenSymbol);
  try {
    const response = await fetch(
      Config.UP_HOST +
        '/zcloak-rest/coinMarketCap/coinPriceQuery?symbol=' +
        tokenSymbol,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    const resObj = await response.json();
    console.log('resObj', resObj);
    if (resObj['code'] == '000000') {
      const data = resObj['data'];
      const result: TokenPrice[] = [];
      for (let i = 0; i < data.length; i++) {
        result.push({
          symbol: data[i]['symbol'],
          price: data[i]['sgdPrice'],
          priceSymbol: 'SGD',
        });
      }
      return result;
    } else {
      return [];
    }
  } catch (error) {
    console.log('coinPriceQuery', error);
  }

  return [];
};

export async function coinCalculatorQuery(
  symbol: string,
  orderId: string,
  decimals: number,
): Promise<PaymentInfo | null> {
  try {
    const response = await fetch(
      Config.UP_HOST +
        '/zcloak-rest/coinMarketCap/coinCalculatorQuery?symbol=' +
        symbol +
        '&transactionId=' +
        orderId,

      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    const resObj = await response.json();
    if (resObj['code'] == '000000') {
      const data = resObj['data'];
      return {
        payTokenAmount: parseValue(data['tokenAmount'] + '', 0, decimals),
        payTokenSymbol: symbol,
        tokenPrice: data['sgdPrice'],
      };
    } else {
      return null;
    }
  } catch (error) {
    console.log('coinCalculatorQuery', error);
  }
  return null;
}

export async function updateOrder(params: UpdateOrderInfo): Promise<boolean> {
  try {
    const response = await fetch(
      Config.UP_HOST + '/zcloak-rest/uniwebOrder/updateOrder',
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
      },
    );
    const resObj = await response.json();
    if (resObj['code'] == '000000') {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.log('updateOrder error', error);
  }

  return false;
}

export const getTestList = async (
  currentPage: number,
  itemsPerPage: number,
) => {
  try {
    const response = await fetch(
      'http://www.jzvcode.com/cccc.php?type=1&currentPage=' +
        currentPage +
        '&itemsPerPage=' +
        itemsPerPage,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    const result = await response.json();
    if (result['code'] == '000000') {
      return result['data'];
    } else {
      return null;
    }
  } catch (error) {
    console.log('getCheckoutConfiguration', error);
  }

  return null;
};

export const getTestDetail = async (id: number) => {
  try {
    const response = await fetch(
      'http://www.jzvcode.com/cccc.php?type=2&id=' + id,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      },
    );
    const result = await response.json();
    if (result['code'] == '000000') {
      return result['data'];
    } else {
      return null;
    }
  } catch (error) {
    console.log('getCheckoutConfiguration', error);
  }

  return null;
};
